package com.chushouya.controller.open;

import com.chushouya.common.annotations.AuthSkip;
import com.chushouya.common.constant.ServiceType;
import com.general.framework.core.lang.Jsons;
import com.chushouya.order.dto.api.shunfeng.ShunfengOrderStatePushDTO;
import com.chushouya.order.dto.api.shunfeng.ShunfengRoutePushDTO;
import com.chushouya.order.dto.api.shunfeng.ShunfengFreightPushDTO;
import com.chushouya.order.service.api.ShunfengPushApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 顺丰推送网关
 */
@RestController
@RequestMapping(ServiceType.OPENAPI + "/shunfeng")
@Slf4j
public class ShunfengPushController {

    @Resource
    private ShunfengPushApiService shunfengPushApiService;

    /**
     * 顺丰订单状态推送回调
     */
    @PostMapping("/pushOrderState")
    @AuthSkip
    public Map<String, String> pushOrderState(@RequestBody ShunfengOrderStatePushDTO requestBody, HttpServletRequest request) {
        log.info("顺丰订单状态推送回调接收到数据: {}", requestBody);
        
        Map<String, String> result = new HashMap<>();
        
        try {
            // 记录请求信息
            String clientIp = getClientIpAddress(request);
            log.info("顺丰订单状态推送 - 客户端IP: {}, 请求ID: {}, 订单数量: {}", 
                    clientIp, requestBody.getRequestId(), 
                    requestBody.getOrderState() != null ? requestBody.getOrderState().size() : 0);
            
            // 调用业务服务处理订单状态推送
            shunfengPushApiService.handleOrderStatePush(requestBody);
            
            result.put("success", "true");
            result.put("code", "0");
            result.put("msg", "");
            return result;
        } catch (Exception e) {
            log.error("顺丰订单状态推送处理失败: ", e);
            result.put("success", "false");
            result.put("code", "1");
            result.put("msg", "处理失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 顺丰路由推送回调
     */
    @PostMapping("/routePushService")
    @AuthSkip
    public Map<String, String> routePushService(@RequestBody ShunfengRoutePushDTO routePushDTO, HttpServletRequest request) {
        log.info("顺丰路由推送回调接收到数据: {}", routePushDTO);
        
        Map<String, String> result = new HashMap<>();
        
        try {
            // 记录请求信息
            String clientIp = getClientIpAddress(request);
            log.info("顺丰路由推送 - 客户端IP: {}", clientIp);
            
            // 调用业务服务处理路由推送
            shunfengPushApiService.handleRoutePush(routePushDTO);
            
            result.put("return_code", "0000");
            result.put("return_msg", "成功");
            return result;
        } catch (Exception e) {
            log.error("顺丰路由推送处理失败: ", e);
            result.put("return_code", "9999");
            result.put("return_msg", "处理失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 顺丰运费推送回调
     */
    @PostMapping("/freightPush")
    @AuthSkip
    public Map<String, String> freightPush(@RequestParam("sign") String sign, 
                                          @RequestParam("content") String content, 
                                          HttpServletRequest request) {
        log.info("顺丰运费推送回调接收到数据 - sign: {}, content: {}", sign, content);
        
        Map<String, String> result = new HashMap<>();
        
        try {
            // 记录请求信息
            String clientIp = getClientIpAddress(request);
            log.info("顺丰运费推送 - 客户端IP: {}, 签名: {}", clientIp, sign);
            
            // 解析content字段为运费数据
            ShunfengFreightPushDTO.ShunfengFreightDataDTO freightData =
                    Jsons.parseObject(content, ShunfengFreightPushDTO.ShunfengFreightDataDTO.class);
            
            // 构建完整的推送DTO
            ShunfengFreightPushDTO freightPushDTO = new ShunfengFreightPushDTO();
            freightPushDTO.setSign(sign);
            freightPushDTO.setFreightData(freightData);
            
            // 调用业务服务处理运费推送
            shunfengPushApiService.handleFreightPush(freightPushDTO);

            result.put("partnerCode", "200");
            result.put("service", "200");
            result.put("code", "200");
            result.put("msgData", "");
            return result;
        } catch (Exception e) {
            log.error("顺丰运费推送处理失败: ", e);
            result.put("partnerCode", "200");
            result.put("service", "200");
            result.put("code", "200");
            result.put("msgData", "");
            return result;
        }
    }

    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}
